﻿using MvcWeb.Data;
using Microsoft.AspNetCore.Mvc;

namespace MvcWeb.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class ApiController : ControllerBase
    {
        /// <summary>
        /// 获取多个股票数据，用|隔开
        /// </summary>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="stocks">股票名: 贵州茅台|平安银行</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetRates(string start, string end, string stocks)
        {
            Dictionary<string, List<double>> result = new Dictionary<string, List<double>>();
            DateTime sDate = DateTime.ParseExact(start, "yyyy-MM", System.Globalization.CultureInfo.CurrentCulture);
            DateTime eDate = DateTime.ParseExact(end, "yyyy-MM", System.Globalization.CultureInfo.CurrentCulture).AddMonths(1);
            
            //对没只股票操作
            foreach (var stock in stocks.Split('|'))
            {
                List<double> rest = new List<double>();
                //指定股票的交易日数据
                var count = GlobalVar.dateTimes.Count - GlobalVar.stocksData[stock].Count;
                var temp = GlobalVar.dateTimes.Skip(count).ToList();

                //指定时间范围内的首个交易日
                var fristV = temp.FirstOrDefault(p => p.Date >= sDate && p.Date < eDate);

                if (fristV != default(DateTime))
                {
                    var lastV = temp.Last(p => p.Date >= sDate && p.Date < eDate);
                    //初始日索引
                    var fIndex = temp.IndexOf(fristV);
                    //结束日索引
                    var lIndex = temp.IndexOf(lastV);
                    for (var i = fIndex; i <= lIndex; i++)
                    {
                        //当日相对上证指数累计收益率     公式为 当日股票价/计算初始日股价 - 当日上证指数 / 计算初始日上证指数 + 1
                        double res = GlobalVar.stocksData[stock][i] / GlobalVar.stocksData[stock][fIndex] - GlobalVar.stocksData["上证指数"][i] / GlobalVar.stocksData["上证指数"][fIndex] + 1;
                        rest.Add(Math.Round(res, 2));
                    }
                }
                result[stock] = rest;
            }

            return Ok(result);
        }

        /// <summary>
        /// 获取指定范围的交易日
        /// </summary>
        /// <param name="start">开始时间</param>
        /// <param name="end">结尾时间</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetDates(string start, string end)
        {
            DateTime sDate = DateTime.ParseExact(start, "yyyy-MM", System.Globalization.CultureInfo.CurrentCulture);
            DateTime eDate = DateTime.ParseExact(end, "yyyy-MM", System.Globalization.CultureInfo.CurrentCulture).AddMonths(1);
            var result = GlobalVar.dateTimes.Where(p=> p.Date >= sDate && p.Date < eDate).Select(p => p.ToString("yyyy-MM-dd"));
            return Ok(result);
        }
    }
}
